import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportUtils {

    public List<Map<Integer,Object>> readExcel(String path,int line) {
        List<Map<Integer,Object>> list = new ArrayList<>();
        InputStream is = null;  //将路径转为输入流对象 输入流对象可以取出来读取
        try {
            is = new FileInputStream(path);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);//将输入流对象存到工作簿对象里面

            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }
                // 循环行Row
                for (int rowNum = (line+1); rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }
                    Map<Integer, Object> item = setValue(hssfRow);
                    list.add(item);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    private Map<Integer,Object> setValue(HSSFRow hssfRow) {
        Map<Integer,Object> map = new HashMap<>();
        for (int i = 0;i<hssfRow.getLastCellNum();i++){
            HSSFCell cell = hssfRow.getCell(i);
            if(cell.getCellTypeEnum().equals(CellType.NUMERIC)){
                map.put(i,cell.getNumericCellValue());
            }else if(cell.getCellTypeEnum().equals(CellType.BOOLEAN)){
                map.put(i,cell.getBooleanCellValue());
            }else if(cell.getCellTypeEnum().equals(CellType.STRING)){
                map.put(i,cell.getStringCellValue());
            }else if(cell.getCellTypeEnum().equals(CellType.BLANK) || cell.getCellTypeEnum().equals(CellType._NONE)){
                map.put(i,null);
            }
        }
        return map;
    }
}
